package com.orz.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class FileUpload
 */

public class FileUpload extends HttpServlet {
	/**
	 * 序列化,用于持久化对象,多个同类型对象能够指向同一个应用
	 * */
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public FileUpload() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 *     
	 * */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		getFileBylib(request);
	}

	/**
	 * 使用FileUpload的文件上传
	 * @param request 从request域中获取文件duixiang
	 * */
	@SuppressWarnings("unchecked")
	private void getFileBylib(HttpServletRequest request) {
	
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("UTF-8"); //设置乱码过滤
			List<FileItem> fileItems;
			try {
				fileItems = upload.parseRequest(request);
				Iterator<FileItem> iter = fileItems.iterator();
				while (iter.hasNext()) {
					FileItem item = iter.next();
					if (!item.isFormField()) { // 表示不是表单的普通属性
						File fi = new File("G:/", item.getName());
						item.write(fi);
						System.out.println("保存文件完成");
					}
				}
			} catch (Exception e) {
				System.out.println("文件上传失败");
			}
		
		
	}

}
